import { Request, Response } from 'express';
import { DepartmentService } from '../services/department-service';
import { CreateDepartmentRequest, UpdateDepartmentRequest } from '../models/Department';

export class DepartmentController {
  // 获取所有部门
  public static async getDepartments(req: Request, res: Response): Promise<void> {
    try {
      const departments = await DepartmentService.getAllDepartments();

      res.json({
        success: true,
        data: departments
      });
    } catch (error) {
      console.error('Error fetching departments:', error);
      res.status(500).json({
        success: false,
        message: '获取部门列表失败'
      });
    }
  }

  // 获取部门树形结构
  public static async getDepartmentTree(req: Request, res: Response): Promise<void> {
    try {
      const departmentTree = await DepartmentService.getDepartmentTree();

      res.json({
        success: true,
        data: departmentTree
      });
    } catch (error) {
      console.error('Error fetching department tree:', error);
      res.status(500).json({
        success: false,
        message: '获取部门树形结构失败'
      });
    }
  }

  // 根据ID获取部门
  public static async getDepartmentById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const department = await DepartmentService.getDepartmentById(id);

      if (!department) {
        res.status(404).json({
          success: false,
          message: '部门不存在'
        });
        return;
      }

      res.json({
        success: true,
        data: department
      });
    } catch (error) {
      console.error('Error fetching department:', error);
      res.status(500).json({
        success: false,
        message: '获取部门信息失败'
      });
    }
  }

  // 创建部门
  public static async createDepartment(req: Request, res: Response): Promise<void> {
    try {
      const departmentData: CreateDepartmentRequest = req.body;

      // 检查部门编码是否已存在
      const existingDepartment = await DepartmentService.getDepartmentByCode(departmentData.code);
      if (existingDepartment) {
        res.status(400).json({
          success: false,
          message: '部门编码已存在'
        });
        return;
      }

      const department = await DepartmentService.createDepartment(departmentData);

      res.status(201).json({
        success: true,
        data: department,
        message: '部门创建成功'
      });
    } catch (error) {
      console.error('Error creating department:', error);
      res.status(500).json({
        success: false,
        message: '创建部门失败'
      });
    }
  }

  // 更新部门
  public static async updateDepartment(req: Request, res: Response): Promise<void> {
    try {
      const departmentData: UpdateDepartmentRequest = req.body;

      // 如果更新编码，检查是否已存在
      if (departmentData.code) {
        const existingDepartment = await DepartmentService.getDepartmentByCode(departmentData.code);
        if (existingDepartment && existingDepartment.id !== departmentData.id) {
          res.status(400).json({
            success: false,
            message: '部门编码已存在'
          });
          return;
        }
      }

      const department = await DepartmentService.updateDepartment(departmentData);

      if (!department) {
        res.status(404).json({
          success: false,
          message: '部门不存在或无变更'
        });
        return;
      }

      res.json({
        success: true,
        data: department,
        message: '部门更新成功'
      });
    } catch (error) {
      console.error('Error updating department:', error);
      res.status(500).json({
        success: false,
        message: '更新部门失败'
      });
    }
  }

  // 删除部门
  public static async deleteDepartment(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      
      await DepartmentService.deleteDepartment(id);

      res.json({
        success: true,
        message: '部门删除成功'
      });
    } catch (error) {
      console.error('Error deleting department:', error);
      
      if (error instanceof Error) {
        res.status(400).json({
          success: false,
          message: error.message
        });
      } else {
        res.status(500).json({
          success: false,
          message: '删除部门失败'
        });
      }
    }
  }

}